// 本地存储工具
const STORAGE_KEY = 'furniture_orders'

export const storage = {
  // 获取所有订单
  getOrders() {
    const data = localStorage.getItem(STORAGE_KEY)
    return data ? JSON.parse(data) : []
  },

  // 保存订单
  saveOrders(orders) {
    localStorage.setItem(STORAGE_KEY, JSON.stringify(orders))
  },

  // 添加订单
  addOrder(order) {
    const orders = this.getOrders()
    const newOrder = {
      ...order,
      id: Date.now(),
      totalAmount: order.quantity * order.unitPrice
    }
    orders.push(newOrder)
    this.saveOrders(orders)
    return newOrder
  },

  // 更新订单
  updateOrder(id, updatedOrder) {
    const orders = this.getOrders()
    const index = orders.findIndex(o => o.id === id)
    if (index !== -1) {
      orders[index] = {
        ...updatedOrder,
        id,
        totalAmount: updatedOrder.quantity * updatedOrder.unitPrice
      }
      this.saveOrders(orders)
      return orders[index]
    }
    return null
  },

  // 删除订单
  deleteOrder(id) {
    const orders = this.getOrders()
    const filtered = orders.filter(o => o.id !== id)
    this.saveOrders(filtered)
    return filtered
  },

  // 初始化示例数据
  initSampleData() {
    const orders = this.getOrders()
    if (orders.length === 0) {
      const sampleOrders = [
        {
          id: 1,
          orderDate: '2024-01-15',
          orderNumber: 'FURN001',
          style: '现代简约沙发',
          size: '2200x900x850',
          quantity: 1,
          unitPrice: 3500,
          totalAmount: 3500
        },
        {
          id: 2,
          orderDate: '2024-01-16',
          orderNumber: 'FURN002',
          style: '实木餐桌',
          size: '1800x800x750',
          quantity: 1,
          unitPrice: 2800,
          totalAmount: 2800
        },
        {
          id: 3,
          orderDate: '2024-01-18',
          orderNumber: 'FURN003',
          style: '布艺床',
          size: '1800x2000x400',
          quantity: 1,
          unitPrice: 4200,
          totalAmount: 4200
        }
      ]
      this.saveOrders(sampleOrders)
    }
  }
}
